package io.github.jyrmc.deploy.task

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * docker deploy task
 *
 * @author jy
 * @since 2023/5/16 11:24
 **/
open class DeployToDockerTask : DefaultTask() {
    @Input
    @Optional
    lateinit var host: String

    @Input
    var port: Int = 22

    @Input
    var username: String = "root"

    @Input
    @Optional
    lateinit var password: String

    @Input
    @Optional
    lateinit var imagePrefix: String

    @Input
    @Optional
    lateinit var imageName: String

    @Input
    @Optional
    lateinit var imageVersion: String


    @TaskAction
    fun deployToDockerAction() {
        if (imageName.isBlank()) {
            println("imageName can't be null or empty")
            return
        }
        if (imageVersion.isBlank()) {
            println("imageVersion can't be null or empty")
            return
        }

        // 部署到docker
        println("Start Deploy To Docker...")
        val commandLine = "docker run -itd --name $imageName ${imagePrefix}/${imageName}:${imageVersion} bash"
        val result = runtimeExec(commandLine)
        println("========================================================================================================================================")
        if (result.isNotEmpty()) {
            println("Deploy Container ID: $result")
        } else {
            println("Deploy Fail!!!")
        }
        println("========================================================================================================================================")
    }

    private fun runtimeExec(commandLine: String): String {
        val process = Runtime.getRuntime().exec(commandLine)
        val inputStream = process.inputStream
        val reader = BufferedReader(InputStreamReader(inputStream))
        val sb = StringBuilder()
        var line: String?
        while (reader.readLine().also { line = it } != null) {
            sb.append(line + "\n");
        }
        process.waitFor()
        inputStream.close()
        reader.close()
        process.destroy()

        return sb.toString()
    }
}